<?php

namespace yak\layui\behaviors;

use yii\db\ActiveRecord;
use yii\web\HeaderCollection;
use yii\web\Request;
use yii\web\Response;

class LayuiEditorBehavior extends LayuiBehavior
{
    public function run(HeaderCollection $headers, Request $request, array $params, Response $response)
    {
        // TODO: Implement run() method.
        $editorClass = $headers->get('Model-Class', null);
        if ($editorClass === null) {
            return $this->fail('editor class model not found!!');
        }

        $method = $headers->get('Model-Method', 'save');

        /**
         * @var ActiveRecord $model
         */
        $model = call_user_func_array([$editorClass, 'findOne'], [$params['Condition']]);
        if ($model->load($params['Data'], '') && call_user_func_array([$model, $method], [])) {
            return $this->success('success');
        }

        if ($model->hasErrors()) {
            return $this->fail(current($model->getFirstErrors()));
        }

        return $this->fail('操作失败!');
    }

}